<template>
  <div class="app-container">
    <el-form ref="datasetForm" :model="datasetForm" :rules="rules" label-width="100px" class="dataset-form">
      <el-form-item label="数据集名称" prop="datasetName">
        <el-input v-model="datasetForm.datasetName" placeholder="请输入数据集名称" maxlength="100" show-word-limit />
      </el-form-item>
      <el-form-item label="数据集编码" prop="datasetCode">
        <el-input v-model="datasetForm.datasetCode" placeholder="请输入数据集编码" maxlength="64" show-word-limit
          @blur="checkDatasetCodeUnique" />
      </el-form-item>
      <el-form-item label="数据集类型" prop="datasetType">
        <el-select v-model="datasetForm.datasetType" placeholder="请选择数据集类型" @change="handleDatasetTypeChange">
          <el-option v-for="item in datasetTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="选择数据源" prop="datasourceId">
        <el-select v-model="datasetForm.datasourceId" placeholder="请选择数据源" @change="handleDatasourceChange">
          <el-option v-for="item in datasourceOptions" :key="item.datasourceId" :label="item.datasourceName"
            :value="item.datasourceId" />
        </el-select>
      </el-form-item>
      <el-form-item label="数据源编码" prop="datasourceCode">
        <el-input v-model="datasetForm.datasourceCode" placeholder="数据源编码" disabled />
      </el-form-item>
      <el-form-item label="数据源名称" prop="datasourceName">
        <el-input v-model="datasetForm.datasourceName" placeholder="数据源名称" disabled />
      </el-form-item>
      <el-form-item label="数据集定义" prop="datasetDefinition" :rules="getDefinitionRules">
        <el-input v-model="datasetForm.datasetDefinition" :placeholder="getDefinitionPlaceholder"
          :rows="isQueryType ? 8 : 1" :type="isQueryType ? 'textarea' : 'text'" :show-word-limit="!isQueryType"
          :maxlength="!isQueryType ? 500 : undefined" />
        <div class="definition-tips" v-if="isQueryType">
          <el-alert title="SQL语句要求" type="info" description="请输入有效的SELECT查询语句，系统会自动限制查询数量以保护性能。" show-icon
            :closable="false" />
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="datasetForm.remark" placeholder="请输入备注信息" maxlength="500" show-word-limit type="textarea"
          rows="3" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleTestConnection">
          测试连接
        </el-button>
        <el-button type="success" @click="handleSubmit" :loading="submitting">
          提交
        </el-button>
        <el-button @click="handleCancel">
          取消
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 测试连接结果对话框 -->
    <el-dialog title="测试连接结果" :visible.sync="testResultVisible" width="600px" :close-on-click-modal="false">
      <div class="test-result-container">
        <div v-if="testResult.success" class="test-success">
          <el-icon class="success-icon"><success-filled /></el-icon>
          <div class="test-message">{{ testResult.message }}</div>
          <div class="test-details">
            <div class="detail-item">
              <span class="detail-label">列数：</span>
              <span class="detail-value">{{ testResult.columnCount }}</span>
            </div>
            <div class="detail-title">列信息：</div>
            <el-table :data="testResult.columns" border style="width: 100%" size="small">
              <el-table-column prop="name" label="列名" width="150" />
              <el-table-column prop="type" label="数据类型" width="150" />
              <el-table-column prop="displayName" label="显示名称" />
            </el-table>
          </div>
        </div>
        <div v-else class="test-error">
          <el-icon class="error-icon"><close-filled /></el-icon>
          <div class="test-message">{{ testResult.message }}</div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createDataset, getDatasourceList, getDatasetTypeList, checkDatasetCodeUnique, testDatasetConnection } from "@/api/system/dataset";
import { Message } from 'element-ui';

export default {
  name: "AddDataset",
  data() {
    return {
      // 表单加载状态
      submitting: false,
      // 数据集表单
      datasetForm: {
        datasetName: "",
        datasetCode: "",
        datasetType: "table", // 默认表类型
        datasourceId: "",
        datasourceCode: "",
        datasourceName: "",
        datasetDefinition: "",
        remark: ""
      },
      // 验证规则
      rules: {
        datasetName: [
          { required: true, message: "请输入数据集名称", trigger: "blur" },
          { min: 1, max: 100, message: "数据集名称长度不能超过100个字符", trigger: "blur" }
        ],
        datasetCode: [
          { required: true, message: "请输入数据集编码", trigger: "blur" },
          { min: 1, max: 64, message: "数据集编码长度不能超过64个字符", trigger: "blur" },
          { pattern: /^[a-zA-Z][a-zA-Z0-9_]{0,63}$/, message: "数据集编码必须以字母开头，只能包含字母、数字和下划线", trigger: "blur" },
          { validator: this.validateDatasetCode, trigger: "blur" }
        ],
        datasetType: [
          { required: true, message: "请选择数据集类型", trigger: "change" }
        ],
        datasourceId: [
          { required: true, message: "请选择数据源", trigger: "change" }
        ]
      },
      // 数据源选项
      datasourceOptions: [],
      // 数据集类型选项
      datasetTypeOptions: [],
      // 测试连接结果对话框
      testResultVisible: false,
      // 测试连接结果
      testResult: {
        success: false,
        message: "",
        columnCount: 0,
        columns: []
      },
      // 编码唯一性验证结果
      codeUnique: true,
      // 初始加载状态
      loading: true
    };
  },
  created() {
    this.init();
  },
  computed: {
    // 是否为查询类型
    isQueryType() {
      return this.datasetForm.datasetType === "query";
    },
    // 根据数据集类型获取定义提示文本
    getDefinitionPlaceholder() {
      switch (this.datasetForm.datasetType) {
        case "table":
          return "请输入表名";
        case "view":
          return "请输入视图名";
        case "query":
          return "请输入SQL查询语句";
        default:
          return "请输入数据集定义";
      }
    },
    // 根据数据集类型获取定义验证规则
    getDefinitionRules() {
      const baseRule = [{ required: true, message: "请输入数据集定义", trigger: "blur" }];

      if (this.isQueryType) {
        // SQL查询类型特殊验证
        return [
          ...baseRule,
          { validator: this.validateQueryDefinition, trigger: "blur" }
        ];
      }

      return baseRule;
    }
  },
  methods: {
    // 初始化
    init() {
      // 获取数据源列表
      getDatasourceList().then(response => {
        this.datasourceOptions = response.data;
      });

      // 获取数据集类型列表
      getDatasetTypeList().then(response => {
        this.datasetTypeOptions = response.data;
      });

      this.loading = false;
    },
    // 数据集类型变更
    handleDatasetTypeChange() {
      this.datasetForm.datasetDefinition = "";
    },
    // 数据源变更
    handleDatasourceChange() {
      if (this.datasetForm.datasourceId) {
        const datasource = this.datasourceOptions.find(item => item.datasourceId === this.datasetForm.datasourceId);
        if (datasource) {
          this.datasetForm.datasourceCode = datasource.datasourceCode;
          this.datasetForm.datasourceName = datasource.datasourceName;
        }
      } else {
        this.datasetForm.datasourceCode = "";
        this.datasetForm.datasourceName = "";
      }
    },
    // 校验数据集编码唯一性
    checkDatasetCodeUnique() {
      console.log(this.datasetForm.datasetCode)
      if (this.datasetForm.datasetCode) {
        checkDatasetCodeUnique(this.datasetForm.datasetCode)
          .then(response => {
            console.log(response)
            this.codeUnique = response == "0";
            console.log(this.codeUnique)
          })
          .catch((error) => {
            console.error("校验数据集编码唯一性失败", error);
            this.codeUnique = false;
          });
      }
    },
    // 编码唯一性验证器
    validateDatasetCode(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入数据集编码"));
      } else if (!this.codeUnique) {
        callback(new Error("数据集编码已存在"));
      } else {
        callback();
      }
    },
    // SQL查询定义验证器
    validateQueryDefinition(rule, value, callback) {
      if (!value) {
        callback(new Error("请输入SQL查询语句"));
      } else {
        // 简单验证是否以SELECT开头
        const trimmedValue = value.trim().toUpperCase();
        if (!trimmedValue.startsWith("SELECT")) {
          callback(new Error("SQL查询语句必须以SELECT开头"));
        } else {
          callback();
        }
      }
    },
    // 测试连接
    handleTestConnection() {
      this.$refs.datasetForm.validate(valid => {
        if (valid) {
          // 准备测试数据
          const testData = {
            datasourceCode: this.datasetForm.datasourceCode,
            datasetType: this.datasetForm.datasetType,
            datasetDefinition: this.datasetForm.datasetDefinition
          };

          this.testResult = { success: false, message: "正在测试连接...", columnCount: 0, columns: [] };
          this.testResultVisible = true;

          // 调用测试接口
          testDatasetConnection(testData)
            .then(response => {
              if (response.code === 200) {
                this.testResult = {
                  success: true,
                  message: "测试成功",
                  columnCount: response.data.columnCount || 0,
                  columns: response.data.columns || []
                };
              } else {
                this.testResult = {
                  success: false,
                  message: response.msg || "测试失败",
                  columnCount: 0,
                  columns: []
                };
              }
            })
            .catch(error => {
              this.testResult = {
                success: false,
                message: error.message || "测试失败，请检查网络或服务",
                columnCount: 0,
                columns: []
              };
            });
        }
      });
    },
    // 提交表单
    handleSubmit() {
      this.$refs.datasetForm.validate(valid => {
        if (valid) {
          this.submitting = true;

          createDataset(this.datasetForm)
            .then(response => {
              this.submitting = false;

              if (response.code === 200) {
                this.$modal.msgSuccess("新增数据集成功");
                this.handleCancel();
              } else {
                this.$modal.msgError(response.msg || "新增数据集失败");
              }
            })
            .catch(error => {
              this.submitting = false;
              this.$modal.msgError("新增数据集失败: " + (error.message || "未知错误"));
            });
        }
      });
    },
    // 取消
    handleCancel() {
      this.$router.push("/data/dataset");
    }
  }
}
</script>

<style scoped>
.dataset-form {
  max-width: 800px;
}

.definition-tips {
  margin-top: 10px;
}

.test-result-container {
  padding: 20px;
  text-align: center;
}

.test-success,
.test-error {
  padding: 20px;
}

.success-icon,
.error-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.success-icon {
  color: #67c23a;
}

.error-icon {
  color: #f56c6c;
}

.test-message {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
}

.test-details {
  text-align: left;
  margin-top: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-label {
  font-weight: bold;
  margin-right: 10px;
}

.detail-title {
  font-weight: bold;
  margin: 15px 0 10px 0;
}
</style>
